<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="add">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <!-- el-table，使用:data属性
           el-table-column，使用prop属性 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column align="center" width="200" label="角色">
          <template slot-scope="{ row }">
            <!-- 条件判断 -->
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" width="200" label="启用">
          <template slot-scope="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state===1?'已启用':'未启用' }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="描述">
          <template slot-scope="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="{row}">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button type="text" size="small" @click="hOK(row)">确认</el-button>
              <el-button type="text" size="small" @click="row.isEdit=false">取消</el-button>
            </template>

            <template v-else>
              <!-- 非编辑状态 -->
              <el-button size="small" type="text" @click="assign(row.id)">分配权限</el-button>
              <el-button size="small" type="text" @click="btnEditRow(row)">编辑</el-button>

              <el-popconfirm
                confirm-button-text="好的"
                cancel-button-text="不用了"
                icon="el-icon-info"
                icon-color="red"
                title="这是一段内容确定删除吗？"
                @onConfirm="hDel(row.id)"
              >
                <el-button slot="reference" size="small" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件
         total:总数据条数
        background 背景色
        page-size:每页条数
        @current-change="hCurrentChange":当前点击的页码触发事件
 -->
        <el-pagination
          :current-page="page"
          :page-sizes="[5,10,15]"
          layout="prev, pager, next,sizes"
          :background="true"
          :page-size="pagesize"
          :total="total"
          @current-change="hCurrenChange"
          @size-change="handleSizeChange"
        />
      </el-row>
    </div>

    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog">
      <el-form ref="formData" :model="formData" :rules="rules">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="formData.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item prop="state" label="启用">
          <el-switch v-model="formData.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="formData.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="hSave">确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 权限组件 -->
    <assign-permission ref="per" :show-dialog-assign.sync="showDialogAssign" :cur-id="curId" />
  </div>
</template>
<script>
import AssignPermission from './components/assignPermission.vue'
import { addRoles, delRoles, getRoles, updateRoles } from '@/api/role'
export default {
  name: 'Role',
  components: {
    AssignPermission
  },
  data() {
    return {
      list: [],
      curId: -1, // 权限id
      total: 0,
      page: 1,
      pagesize: 5,
      showDialog: false, // 弹框
      showDialogAssign: false, // 权限弹框
      formData: {
        name: '',
        state: 1, // 默认未1启用 关闭 0 打开1
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getRole()
  },
  methods: {
    // 获取-分页查询角色列表
    async getRole() {
      const res = await getRoles({ page: this.page, pagesize: this.pagesize })
      // console.log(res)
      this.list = res.data.rows
      this.list.forEach(it => {
        this.$set(it, 'isEdit', false)
        // this.$set(对象,新添加的属性名,属性值)
        // isEdit = true
        this.$set(it, 'editRow', {
          id: it.id,
          name: it.name,
          state: it.state,
          description: it.description
        })
      })
      // console.log(this.list)
      this.total = res.data.total
    },
    hCurrenChange(page) {
      // 1.更新页码
      this.page = page
      // 2.重发请求
      this.getRole()
    },
    handleSizeChange(val) {
      // 1.更新每页显示的数据
      this.pagesize = val
      // 2.更新页码为1
      this.page = 1
      // 3.重发请求
      this.getRole()
      console.log(`每页 ${val} 条`)
    },
    // 点击新增 展示弹框
    add() {
      this.showDialog = true // 打开弹层
    },
    // 表单校验
    hSave() {
      this.$refs.formData.validate(valid => {
        valid && this.doAdd()
      })
    },
    // 添加功能
    async doAdd() {
      await addRoles(this.formData)
      // console.log(res)
      this.$message.success('新增角色成功')
      // 更新表格 添加后显示添加的位置
      this.total = this.total + 1
      // Math.ceil向上取整
      this.page = Math.ceil(this.total / this.pagesize)
      this.getRole()
      this.btnCancel()
    },
    btnCancel() {
      this.$refs.formData.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹层
    },
    // 点击编辑行
    btnEditRow(row) {
      row.isEdit = true // 改变行的编辑状态
    },
    // 确认编辑
    async hOK(row) {
      // 判断是否必填
      console.log(row)
      if (!row.editRow.name || !row.editRow.description) {
        this.$message.error('请填写正确内容')
      }
      // 调用接口
      await updateRoles(row.editRow)
      // 退出编辑
      // eslint-disable-next-line require-atomic-updates
      row.isEdit = false
      // 重发请求
      this.getRole()
    },
    // 删除
    async hDel(id) {
      console.log(id)
      await delRoles(id)
      this.$message.success('删除成功')
      // 如果是当前页的最后一条数据,要向前翻一页
      if (this.list.length === 1) {
        if (this.page > 1) { this.page-- }
      }
      this.getRole()
    },
    // 打开分配权限的弹框
    assign(id) {
      // console.log(id)
      this.showDialogAssign = true
      this.curId = id
      // 调用子组件的方法
      this.$nextTick(() => {
        this.$refs.per.assign()
      })
    }

  }
}
</script>

<style scoped>
.role-operate {
  padding: 10px;
}
</style>
